package com.alibaba.citrus.ots.unified.inventory.facade.service;


import com.alibaba.citrus.ots.common.exception.FacadeException;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.db.service.CustomSequenceAccessor;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.alibaba.lattice2.epoch.sdk.oss.EpochOssService;
import com.alibaba.lattice2.epoch.user.dto.LoginUser;
import com.alibaba.lattice2.epoch.user.service.EpochLoginUserService;
import com.epoch.app.bcots.model.dto.*;
import com.epoch.app.bcots.service.BaseDataService;
import com.epoch.app.otsunifiedinventory.model.dto.*;
import com.epoch.app.otsunifiedinventory.model.enums.SurplusInventoryStatus;
import com.epoch.app.otsunifiedinventory.ouisurplusinventoryorder.dto.LoadResponse;
import com.epoch.app.otsunifiedinventory.ouisurplusinventoryorder.service.OuiSurplusInventoryOrderService;
import com.epoch.app.otsunifiedinventory.ouisurplusinventoryorderdetail.service.OuiSurplusInventoryOrderDetailService;
import com.epoch.app.otsunifiedinventory.service.OtsUnifiedInventoryService;
import com.epoch.app.otsunifiedinventory.surplusinventoryread.service.SurplusInventoryReadService;
import com.taobao.diamond.utils.JSONUtils;
import com.taobao.diamond.utils.StringUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @author Chen.mu
 * @date 2021/11/8
 */
@Component
public class SurplusInventoryServiceImpl implements SurplusInventoryReadService {
    @Autowired
    OuiSurplusInventoryOrderService ouiSurplusInventoryOrderService;
    @Autowired
    OuiSurplusInventoryOrderDetailService ouiSurplusInventoryOrderDetailService;
    @Autowired
    BaseDataService baseDataService;
    @Autowired
    EpochOssService epochOssService;
    @Autowired
    EpochLoginUserService epochLoginUserService;
    @Autowired
    CustomSequenceAccessor customSequenceAccessor;
    @Autowired
    OtsUnifiedInventoryService otsUnifiedInventoryService;
    @Override
    public Result<List<SurplusInventoryResponse>> loadList(SurplusOrderQueryRequest surplusOrderQueryRequest) {
        Result<List<SurplusInventoryResponse>> listResponse = ouiSurplusInventoryOrderService.loadList(surplusOrderQueryRequest);
        List<String> ids = new ArrayList<>();
        if(listResponse.isSuccess()&& !CollectionUtils.isEmpty(listResponse.getResult())) {
            listResponse.getResult().forEach(x -> {
                ids.add(x.getReceiveGroupId());
                ids.add(x.getSubmitGroupId());
            });
            Map<String, OrganizationSDO> groupMap = getOrganizations(ids);

            listResponse.getResult().forEach(x -> {
                if (groupMap.get(x.getReceiveGroupId()) != null) {
                    x.setReceiveGroupName(groupMap.get(x.getReceiveGroupId()).getName());
                }
                if (groupMap.get(x.getSubmitGroupId()) != null) {
                    x.setSubmitGroupName(groupMap.get(x.getSubmitGroupId()).getName());
                }
                LoginUser user= null;
                try {
                    user = (LoginUser) JSONUtils.deserializeObject(x.getCreator(), LoginUser.class);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if(x.getStatus().intValue()==SurplusInventoryStatus.WAIT_EXAMINE.getValue().intValue()){
                    FindTaskByInsatanceIdRequest request=new FindTaskByInsatanceIdRequest();
                    request.setInstanceId(x.getFlowId());
                    FindTaskByInsatanceIdResponse assigneeUsers= otsUnifiedInventoryService.findTaskByInsatanceId(request);
                   if( assigneeUsers.getResult()!=null){
                       StringBuffer sb=new StringBuffer();
                       assigneeUsers.getResult().forEach(t->sb.append(t+","));
                       x.setAuditors(sb.toString());
                   }else {
                       x.setAuditors("-");
                   }
                }else{
                    x.setAuditors("-");
                }
                x.setCreator(user.getRealName());
                x.setIntermediary(user.getRealName());
                x.setStatusDesc(getStatusDesc(x.getStatus()));
            });
        }
        return listResponse;
    }
    private String getStatusDesc(Integer status){
        for (SurplusInventoryStatus value : SurplusInventoryStatus.values()) {
                if (Objects.equals(value.getValue(),status)){
                    return value.getLabel();
                }
            }
            return null;
    }
    @Override
    public Result<SurplusInventoryWithGoodsResponse> load(SurplusOrderQueryRequest surplusOrderQueryRequest) {
        LoadResponse loadResponse = ouiSurplusInventoryOrderService.load(surplusOrderQueryRequest);
        if (loadResponse.getResult() != null) {
            SurplusInventoryWithGoodsResponse surplusInventoryWithGoodsResponse = new SurplusInventoryWithGoodsResponse();
            BeanUtils.copyProperties(loadResponse.getResult(), surplusInventoryWithGoodsResponse);
            OuiSurplusInventoryOrderDetailLoadListVO requet = new OuiSurplusInventoryOrderDetailLoadListVO();
            requet.setSiOrderId(loadResponse.getResult().getSiOrderId());

            Result<List<SurplusInventoryDetailResponse>> detailList = ouiSurplusInventoryOrderDetailService.loadList(requet);
            SearchScItemRequest searchScItemRequest=new SearchScItemRequest();
            Map<String,List<String>> outerIdList=new HashMap<>();
            outerIdList.put("scItemIds",detailList.getResult().stream().map(x->x.getScItemId()).collect(Collectors.toList()));
            searchScItemRequest.setSearchReqDTO(outerIdList);
            Result<List<ScItemSDO>> scItemResult =baseDataService.searchScItem(searchScItemRequest);
            Map<String,ScItemSDO> scItems=scItemResult.getResult().stream().collect(Collectors.toMap(x -> x.getScItemId(), x -> x, (v1, v2) -> v2));
            detailList.getResult().forEach(x->{
                if(x.getPrice()!=null) {
                    x.setPrice(x.getPrice().divide(BigDecimal.valueOf(1000), RoundingMode.DOWN));
                }else{
                    x.setPrice(new BigDecimal(0));
                }
                if(x.getPreFee()!=null) {
                    x.setPreFee(x.getPreFee().divide(BigDecimal.valueOf(1000), RoundingMode.DOWN));
                }else{
                    x.setPreFee(new BigDecimal(0));
                }

                ScItemSDO tmp =scItems.get(x.getScItemId());
                if(tmp!=null) {
                    x.setTitle(tmp.getTitle());
                    x.setOuterId(tmp.getOuterId());
                }else{
                    x.setTitle("货品不存在");
                    x.setOuterId("货品不存在");
                }
            });
            if(!StringUtils.isEmpty(loadResponse.getResult().getAuditors())) {
                surplusInventoryWithGoodsResponse.setGoodsList(detailList.getResult());
                AuditorIdTransResp auditorIdTransResp = new AuditorIdTransResp();
                auditorIdTransResp= JSONObject.parseObject(loadResponse.getResult().getAuditors(), AuditorIdTransResp.class);
                surplusInventoryWithGoodsResponse.setAuditorIdList1(auditorIdTransResp.getAuditorIdList1());
                surplusInventoryWithGoodsResponse.setAuditorIdList2(auditorIdTransResp.getAuditorIdList2());
                surplusInventoryWithGoodsResponse.setAuditorIdList3(auditorIdTransResp.getAuditorIdList3());
            }
            surplusInventoryWithGoodsResponse.setFiles(JSONObject.parseArray(surplusInventoryWithGoodsResponse.getImgUrl(),String.class));
            return Result.success(surplusInventoryWithGoodsResponse);
        }

        throw new FacadeException("");
    }

    /**
     * 获取组织map
     *
     * @param ids
     * @return
     */
    private Map<String, OrganizationSDO> getOrganizations(List<String> ids) {
        BaselineGetOrganizationByIds2Request request = new BaselineGetOrganizationByIds2Request();
        request.setIds(ids);
        BaselineGetOrganizationByIds2Response groupResp = baseDataService.baselineGetOrganizationByIds2(request);
        Map<String, OrganizationSDO> map = groupResp.getResult().stream().collect(Collectors.toMap(OrganizationSDO::getId, x -> x, (x1, x2) -> x1));
        return map;
    }
}
